﻿//------------------------------------------------------------------------------
// System Name:    Customer Service Platform
// Component:      Role Assignment control
// Created By:     Parker Zhou (parkerz@wicresoft.com)
// Created Date:   2011-1-27
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASBCC.Business;
using ASBCC.Database.EntityFramework;

namespace BEGDC.CC.Web.ACR.Administration
{
    //TODO: Refactory it!

    /// <summary>
    /// Role Assignment Module common Control
    /// Parent page should at least have a Control with ID:"BelongsTo",
    /// and hard code the Text property with module name like "Admin"、"CCD"...
    /// from enum SystemModule
    /// </summary>
    public partial class RoleAssignmentCommon : System.Web.UI.UserControl
    {
        /// <summary>
        /// Get BelongsTo from parent Page Control "BelongsTo"
        /// </summary>
        /// <returns></returns>
        private string GetBelongsTo()
        {
            HiddenField hr = this.Page.FindControl("BelongsTo") as HiddenField;
            if (hr == null)
            {
                throw new NullReferenceException("Missing hidden for BelongsTo");
            }
            return hr.Value;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (GetBelongsTo() == "Admin")
            {
                this.gvUserRoleInfo.DataSourceID = "edsUserRoleInfoAdmin";
                this.dvUserRole.DataSourceID = "edsUserRoleInfoAdmin";
            }
            else
            {
                this.gvUserRoleInfo.DataSourceID = "edsUserRoleInfoOther";
                this.dvUserRole.DataSourceID = "edsUserRoleInfoOther";
            }
        }

        protected void gvUserRoleInfo_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = gvUserRoleInfo.SelectedIndex;

            if (index != -1)
            {
                dvUserRole.PageIndex = index + gvUserRoleInfo.PageIndex * gvUserRoleInfo.PageSize;
                dvUserRole.ChangeMode(DetailsViewMode.Edit);

                BindWhereClause();
                BindOrderByClause();

                dvUserRole.DataBind();
                this.BtnAdd.Visible = false;
                dvUserRole.Visible = true;
                ((TextBox)this.dvUserRole.Rows[0].Cells[1].Controls[0]).ReadOnly = true;
            }
        }

        private void BindWhereClause()
        {
            if (!string.IsNullOrEmpty(SearchText.Text))
            {
                if (this.gvUserRoleInfo.DataSourceID == "edsUserRoleInfoAdmin")
                    this.edsUserRoleInfoAdmin.Where += " and (it.NameEN like '%" + SearchText.Text + "%'" + " or it.EmployeeNo like '%" + SearchText.Text + "%')";
                else
                    this.edsUserRoleInfoOther.Where += " and (it.NameEN like '%" + SearchText.Text + "%'" + " or it.EmployeeNo like '%" + SearchText.Text + "%')";
            }

        }

        private void BindOrderByClause()
        {
            if (!string.IsNullOrEmpty(gvUserRoleInfo.SortExpression))
            {
                if (this.gvUserRoleInfo.DataSourceID == "edsUserRoleInfoAdmin")
                    edsUserRoleInfoAdmin.OrderBy = "it." + gvUserRoleInfo.SortExpression + " "
                        + PageHelper.SortDirections[(int)gvUserRoleInfo.SortDirection];
                else
                    edsUserRoleInfoOther.OrderBy = "it." + gvUserRoleInfo.SortExpression + " "
                        + PageHelper.SortDirections[(int)gvUserRoleInfo.SortDirection];
            }
        }

        protected void BtnAdd_Click(object sender, EventArgs e)
        {
            this.BtnAdd.Visible = false;
            dvUserRole.ChangeMode(DetailsViewMode.Insert);
            dvUserRole.DataBind();
            dvUserRole.Visible = true;
        }

        protected void dvUserRole_ItemCommand(object sender, DetailsViewCommandEventArgs e)
        {
            if (e.CommandName == "Insert"
                   || e.CommandName == "Update"
                   || e.CommandName == "Cancel")
            {
                dvUserRole.Visible = false;
                this.BtnAdd.Visible = true;
            }
        }

        protected void Search_Click(object sender, EventArgs e)
        {
            //_searchKey = (this.FindControl("SearchText") as TextBox).Text;
            //gvUserInfo.DataBind();
            //dvUserRole.Visible = false;
            //BtnAdd.Visible = true;

            BindWhereClause();
            BindOrderByClause();

            gvUserRoleInfo.DataBind();
            dvUserRole.Visible = false;

        }

        protected void Clear_Click(object sender, EventArgs e)
        {
            //_searchKey = string.Empty;
            //gvUserInfo.DataBind();
            //dvUserRole.Visible = false;
            //BtnAdd.Visible = true;

            SearchText.Text = null;
            Search_Click(sender, e);
        }

        protected void gvUserRoleInfo_PageIndexChanged(object sender, EventArgs e)
        {
            dvUserRole.Visible = false;
        }

        protected void edsUserRoleInfoAdmin_Inserting(object sender, EntityDataSourceChangingEventArgs e)
        {
            InsertEmployee(e);
            e.Cancel = true;
        }

        protected void edsUserRoleInfoAdmin_Updating(object sender, EntityDataSourceChangingEventArgs e)
        {
            //var user = e.Entity as Employee;
            //var selectedRoles = Request.Form["ChooseRoles"];
            //var roles = e.Context.CreateQuery<Role>("[Role]");

            //user.Roles.Load();
            //user.Roles.Clear();

            //foreach (var r in selectedRoles.Split(','))
            //{
            //    int rid = int.Parse(r);
            //    user.Roles.Add(roles.First(p => p.RoleID == rid));
            //}
            UpdateEmployee(e);
            e.Cancel = true;
        }

        protected void edsUserRoleInfoOther_Inserting(object sender, EntityDataSourceChangingEventArgs e)
        {
            InsertEmployee(e);
            //添加该用户的操作日志
            IPrincipal user = (IPrincipal)(Context.User);
            var dc = e.Context;
            var employee = e.Entity as Employee;
            var employeeNO = RoleAssignmentHelper.getEmployeeNo(employee.NameEN);
            if (string.IsNullOrEmpty(employeeNO))
            {
                e.Cancel = true;
                return;
            }
            string employeeNo = Convert.ToString(employeeNO);

            //
            if (GetBelongsTo() == SystemModule.CID.ToString())
            {
                GlobalHelper.LogOperation(user.Identity.Name, SystemModule.CID, "RoleAssignment inserted. id=" + employeeNo + "; name=" + employee.NameEN + "; roles=" + GetRoles(employeeNo));
            }
            if (GetBelongsTo() == SystemModule.CIO.ToString())
            {
                GlobalHelper.LogOperation(user.Identity.Name, SystemModule.CIO, "RoleAssignment inserted. id=" + employeeNo + "; name=" + employee.NameEN + "; roles=" + GetRoles(employeeNo));
            }
            if (GetBelongsTo() == SystemModule.ACR.ToString())
            {
                GlobalHelper.LogOperation(user.Identity.Name, SystemModule.ACR, "RoleAssignment inserted. id=" + employeeNo + "; name=" + employee.NameEN + "; roles=" + GetRoles(employeeNo));
            }
            if (GetBelongsTo() == SystemModule.Admin.ToString())
            {
                GlobalHelper.LogOperation(user.Identity.Name, SystemModule.Admin, "RoleAssignment inserted. id=" + employeeNo + "; name=" + employee.NameEN + "; roles=" + GetRoles(employeeNo));
            }

            e.Cancel = true;
        }

        protected void edsUserRoleInfoOther_Updating(object sender, EntityDataSourceChangingEventArgs e)
        {
            UpdateEmployee(e);

            //添加该用户的修改日志
            IPrincipal user = (IPrincipal)(Context.User);
            var dc = e.Context;
            var employee = e.Entity as Employee;
            var employeeNO = RoleAssignmentHelper.getEmployeeNo(employee.NameEN);
            string employeeNo = Convert.ToString(employeeNO);

            if (GetBelongsTo() == SystemModule.CID.ToString())
            {
                GlobalHelper.LogOperation(user.Identity.Name, SystemModule.CID, "RoleAssignment updated. id=" + employeeNo + "; name=" + employee.NameEN + "; roles=" + GetRoles(employeeNo));
            }
            if (GetBelongsTo() == SystemModule.CIO.ToString())
            {
                GlobalHelper.LogOperation(user.Identity.Name, SystemModule.CIO, "RoleAssignment updated. id=" + employeeNo + "; name=" + employee.NameEN + "; roles=" + GetRoles(employeeNo));
            }
            if (GetBelongsTo() == SystemModule.ACR.ToString())
            {
                GlobalHelper.LogOperation(user.Identity.Name, SystemModule.ACR, "RoleAssignment updated. id=" + employeeNo + "; name=" + employee.NameEN + "; roles=" + GetRoles(employeeNo));
            }
            if (GetBelongsTo() == SystemModule.Admin.ToString())
            {
                GlobalHelper.LogOperation(user.Identity.Name, SystemModule.Admin, "RoleAssignment updated. id=" + employeeNo + "; name=" + employee.NameEN + "; roles=" + GetRoles(employeeNo));
            }

        }

        //TODO: remove logic code to BL
        private void InsertEmployee(EntityDataSourceChangingEventArgs e)
        {
            var user = e.Entity as Employee;
            string newEm = user.NameEN;
            //string newEm = e.Values["NameEN"].ToString();
            ////maybe empty em
            if (newEm == null) return;
            string chooseRolesStr;
            if (Request.Form["ChooseRoles"] == null) chooseRolesStr = string.Empty;
            else
                chooseRolesStr = Request.Form["ChooseRoles"].ToString();


            List<int> choseRoles = new List<int>();
            foreach (string rstr in chooseRolesStr.Split(','))
            {
                if (!string.IsNullOrEmpty(rstr))
                    choseRoles.Add(Convert.ToInt32(rstr));
            }
            RoleAssignmentHelper arh = new RoleAssignmentHelper();
            if (arh.SetUserRoles(newEm, choseRoles, GetBelongsTo(), false) == false)
            {
                e.Cancel = true;
                Page.RegisterClientScriptBlock("", "<script type=\"text/javascript\">alert(\"查无此人，请核实后重新输入！\");</script>");
                return;
            }
            BindWhereClause();
            BindOrderByClause();

            gvUserRoleInfo.DataBind();

            //添加该用户可访问ACR的project
            if (GetBelongsTo() == SystemModule.ACR.ToString() || GetBelongsTo() == SystemModule.Admin.ToString())
                arh.CreateProjectMembers(newEm);
            //gvUserInfo.DataBind();
        }

        //TODO: remove logic code to BL
        private void UpdateEmployee(EntityDataSourceChangingEventArgs e)
        {
            var user = e.Entity as Employee;
            string emNo = user.EmployeeNo;
            if (emNo == null) throw new NullReferenceException("emNo");
            string chooseRolesStr;
            if (Request.Form["ChooseRoles"] == null) chooseRolesStr = string.Empty;
            else
                chooseRolesStr = Request.Form["ChooseRoles"].ToString();

            List<int> choseRoles = new List<int>();
            foreach (string rstr in chooseRolesStr.Split(','))
            {
                if (!string.IsNullOrEmpty(rstr))
                    choseRoles.Add(Convert.ToInt32(rstr));
            }
            RoleAssignmentHelper arh = new RoleAssignmentHelper();
            arh.SetUserRoles(emNo, choseRoles, GetBelongsTo(), true);


            gvUserRoleInfo.DataBind();

        }

        //TODO: remove logic code to BL
        protected string GetRoles(string employeeNo)
        {
            if (employeeNo == null) throw new NullReferenceException("EmployeeNo");

            using (var dc = new CCEntities())
            {
                var employee = dc.Employees.First(e => e.IsEnabled == true && e.EmployeeNo == employeeNo);
                string belongsTo = GetBelongsTo();
                employee.Roles.Load();
                IEnumerable<Role> roles;
                if (belongsTo == SystemModule.Admin.ToString())
                    roles = employee.Roles.Where(r => !r.Disabled && r.IsAdmin);
                else
                    roles = employee.Roles.Where(r => !r.Disabled && r.BelongsTo == belongsTo);

                return string.Join(",", roles.Select(r => r.Name).ToArray());

            }
        }

        //TODO: remove logic code to BL
        protected string GetIsAdmin(string employeeNo)
        {
            if (employeeNo == null) throw new NullReferenceException("EmployeeNo");
            string belongsTo = GetBelongsTo();
            if (belongsTo == SystemModule.Admin.ToString()) return "True";
            using (var dc = new CCEntities())
            {
                var employee = dc.Employees.First(e => e.IsEnabled == true && e.EmployeeNo == employeeNo);
                employee.Roles.Load();
                if (employee.Roles.Count(r => !r.Disabled && r.BelongsTo == belongsTo && r.IsAdmin) > 0)
                    return "True";
                else
                    return "False";
            }
        }

        protected void gvUserRoleInfo_Sorted(object sender, EventArgs e)
        {
            this.dvUserRole.Visible = false;
            this.BtnAdd.Visible = true;
        }






    }
}
